//测试vscode如何提交项目修改文件到码云
const http = require('http');
const path = require('path');
const querystring = require('querystring');

const express = require('express');
const bodyParser = require('body-parser');
const multer = require('multer');
const favicon = require('serve-favicon');

const tracer = require('tracer').colorConsole();

const config = require('./config');

const app = express();

//处理页面数据 
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

//静态模板声明
app.use(express.static('public'));
app.use('/lib', express.static(path.join(__dirname, 'node_modules')));

//网页图标
app.use(favicon('public/assets/image/logo.png'));


//app.listen(config.app.port);
//tracer.info('服务已启动', `http://127.0.0.1:${config.app.port}`);
tracer.info('服务已启动', `http://127.0.0.1:8000`);

app.use('/*', function (req, res, next) {
    // tracer.info(req);
    // tracer.info('Host name', req.hostname);
    // tracer.info('Original URL', req.originalUrl);
    // tracer.info('客户端', req.ips);
    // tracer.info('Base URL', req.baseUrl);
    // tracer.info('Path', req.path);
    // tracer.info('Method', req.method);
    // tracer.info('Query', req.query);
    // tracer.info('Params', req.params);
    tracer.info('Body', req.body);
    next();
});


app.use('/', function (req, res) {
    
    if (req.body) {
        tracer.info(req.body);
    }
    let option = {
        hostname: config.backend.host,
        port: config.backend.port,
        path: req.baseUrl + req.path,
        method: req.method,
        headers: {
            'Content-Type': 'application/json',
            'charset': 'utf-8',
        }
    };
    let request = http.request(option, (response) => {
        response.setEncoding('utf8');
        let rawData = '';
        response.on('data', (chunk) => {
            rawData += chunk;
        }).on('end', () => {
            res.json(JSON.parse(rawData)) || res.json({message: 'ERROR'});
        })
    })
    request.on('error', (e) => {
        tracer.error(e);
    })
    request.write(JSON.stringify(req.body) + '\n');
    request.end();
});
app.listen(8000);